import { ref } from "vue"
import type { UnwrapRef } from "vue"

// 异步请求函数
export function useAsync<T>(asyncFn:()=> Promise<T>, initValue: T, immediate = true){
    const pending = ref(false)
    const data = ref(initValue)
    const error = ref(null)

    // 执行异步请求
    const execute = async () => {
        pending.value = true
        error.value = null
        return asyncFn().then(
            (res) => {
                data.value = res as UnwrapRef<T>
                pending.value = false   
            },
            (err) => {
                error.value = err
                pending.value = false
            }
        ).catch(err => {
            error.value = err
            pending.value = false
        })
    }

    if(immediate){
        execute()
    }

    return {
        pending, // 请求状态
        data,    // 返回数据
        error,   // 错误信息
        execute  // 执行请求函数
    }
}















